﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
using System.Security.AccessControl;
using SHDocVw;
using System.Xml.Serialization;


namespace OfficeClip.OpenSource.SpellO
{
	public enum LogState
	{
		None = 0,
		Pass = 1,
		Fail = 2,
		Warning = 3,
		Debug = 4,
		Title = 5,
		SubTitle = 6,
		Error = 7,
		FatalError = 8,
		Info = 9,
		Event = 10,
		Property = 11,
		Function = 12
	}

	public enum LogLevel
	{
		OFF = 0,
		FATAL = 1,
		ERROR = 2,
		WARNING = 3,
		INFO = 4,
		DEBUG = 5,
		ALL = 6
	}

	public class Constants
	{
		public static int LineNum = 0;
		public static bool IsError = false;
		public static string ErrorMessage = string.Empty;
		public static int SqlCommandTimeout = 480;
		public static string VirtualDirectory = "OfficeClip";

		public static string GetSetupDir()
		{
			System.Reflection.Assembly Asm = System.Reflection.Assembly.GetExecutingAssembly();
			return Path.GetDirectoryName(Asm.Location);
		}

		public static string GetAppVersion()
		{
			return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
		}

		/// <summary>
		/// Creates a COM object given it's ProgID.
		/// </summary>
		/// <param name="sProgID">The ProgID to create</param>
		/// <returns>The newly created object, or null on failure.</returns>
		public static object COMCreateObject(string sProgID)
		{
			// We get the type using just the ProgID
			Type oType = Type.GetTypeFromProgID(sProgID);
			if (oType != null)
			{
				return Activator.CreateInstance(oType);
			}

			return null;
		}

		/// <summary>
		/// Opens a new Internet Explorer window and navigates it to the URL.
		/// This code is for demonstration purposes only.
		/// </summary>
		/// <param name="sURL">URL to navigate to.</param>
		/// <returns>true all the time.</returns>
		public static bool IEOpenOnURL(Log log, string sURL)
		{
			if (log != null)
			{
				log.WriteFunction("IEOpenOnURL", "log", sURL, "", "");
			}
			try
			{
				InternetExplorer oIE = (InternetExplorer)COMCreateObject
											 ("InternetExplorer.Application");
				if (oIE != null)
				{
					object oEmpty = String.Empty;
					object oURL = sURL;
					oIE.Visible = true;
					oIE.Navigate2(ref oURL, ref oEmpty, ref oEmpty, ref oEmpty, ref oEmpty);
				}
			}
			catch (Exception e)
			{
				log.WriteError("COM", e.Message);
			}
			return true;
		}

		public static void MimimizeWindow(System.Diagnostics.Process process)
		{
			System.Int32 SW_MINIMIZE = 6;
			System.Diagnostics.Process[] myProcess = System.Diagnostics.Process.GetProcessesByName(process.ProcessName);
			System.IntPtr hwnd = myProcess[0].MainWindowHandle;
			ShowWindow(hwnd, SW_MINIMIZE);
		}

		public static void ProvideFileFullAccess(string filePath)
		{
			try
			{
				FileSecurity security = File.GetAccessControl(filePath);

				FileSystemAccessRule rule =
					new FileSystemAccessRule(@"Everyone", FileSystemRights.FullControl, AccessControlType.Allow);

				security.AddAccessRule(rule);

				File.SetAccessControl(filePath, security);
			}
			catch
			{
				// ignore all errors
			}
		}

		public static void ProvideFullAccess(string folder)
		{
			// In vista this does not work as we need to get the SeSecurityPrivilege access. In the meantime
			// we have to ignore this in case of any exception
			try
			{
				System.Security.AccessControl.DirectorySecurity sec
				= Directory.GetAccessControl(folder);
				sec.SetSecurityDescriptorSddlForm("D:PAI(A;OICI;FA;;;WD)"); // Gives full access to all the files in this folder
				Directory.SetAccessControl(folder, sec);
			}
			catch
			{
			}
		}

		public static void Serialize(Settings.SpellO spello)
		{
			XmlSerializer s = new XmlSerializer(typeof(Settings.SpellO));
			TextWriter w = new StreamWriter(GetSetupDir() + @"\settings.xml");
			s.Serialize(w, spello);
			w.Close();
		}

		public static Settings.SpellO Deserialize()
		{
			string path = GetSetupDir() + @"\settings.xml";
			if (!File.Exists(path)) {
				File.Copy(GetSetupDir() + @"\settingsDefault.xml", path, true);
			}
			XmlSerializer s = new XmlSerializer(typeof(Settings.SpellO));
			Settings.SpellO newList;
			TextReader r = new StreamReader(path);
			newList = (Settings.SpellO)s.Deserialize( r );
			r.Close();
			return newList;
		}

		[DllImport("user32.dll")]
		private static extern Boolean ShowWindow(IntPtr hWnd, Int32 nCmdShow);

	}
}
